#include <iostream>
#include <stdlib.h>
#include <windows.h>

#include <gl/glew.h>
#define GLFW_DLL
#include <GL/glfw.h>

#include "gamestate.h"
#include "inputhandler.h"

#include "renderer/renderer.h"

#include "sim/simbase.h"
#include "sim/simworld.h"
#include "sim/simyard.h"

int main( void ){
    int running = GL_TRUE;
    int lastTime;
    int dt;
    int width = 1024;
    int height = 768;
    bool shipyardmode = true;

    // Initialize GLFW
    if( !glfwInit() ){
        exit( EXIT_FAILURE );
    }
    // Open an OpenGL window
    if( !glfwOpenWindow( width, height, 0,0,0,0,0,0, GLFW_WINDOW ) ){
        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    if(glewInit()==GLEW_OK){
        std::cout<<"GLEW init ok\n";
    }
    else{
        std::cout<<"GLEW init NOT ok\n";
    }

    // set the projection matrix to a normal frustum with a max depth of 50
    gamestate = new GameState();
    inputHandler = new InputHandler();
    renderer = new Renderer(width, height);

    if(shipyardmode){
        simulation = new SimYard();
    }
    else{
        simulation = new SimWorld();
    }

    glfwSetMouseButtonCallback(InputHandler::MouseClick);
    glfwSetWindowSizeCallback(Renderer::WindowResizeCallback);

    simulation->Setup();
    renderer->Initialise();
    lastTime = GetTickCount();
    // Main loop
    while( running )
    {
        dt = GetTickCount() - lastTime;
        if(dt == 0){
            dt = 1;
        }
        lastTime = GetTickCount();

        simulation->Update(dt);
        renderer->Draw();
        // Check if ESC key was pressed or window was closed
        running = !glfwGetKey( GLFW_KEY_ESC ) && glfwGetWindowParam( GLFW_OPENED );

    }
    // Close window and terminate GLFW
    glfwTerminate();
    // Exit program
//    exit( EXIT_SUCCESS );
//    exit(0);
}
